<template>
  <a-layout-header style="background: #fff; padding: 0">
    <a-row style="background: #6495ed; height: 50px">
      <a-col :span="24">
        <a-icon
          class="trigger"
          :type="collapsed ? 'menu-unfold' : 'menu-fold'"
          @click="() => (collapsed = !collapsed)"
        />
        <a-button @click="delete_userinfo">退出登录</a-button>

        <a-button type="primary" @click="showDrawer"> 聊天 </a-button>
        <a-drawer
          :title="'在线人数：' + people_num"
          width="520"
          :closable="false"
          :visible="visible"
          @close="onClose"
        >
          <div v-for="item in online_list" :key="item.uid">
            <a-button type="primary" @click="showChildrenDrawer(0)">
              联系客服
            </a-button>
            <a-button type="primary" @click="showChildrenDrawer(item.uid)">
              {{ item.nickname ? item.nickname : item.username }}
            </a-button>
          </div>
          <a-drawer
            title="Two-level Drawer"
            width="500"
            :closable="false"
            :visible="childrenDrawer"
            @close="onChildrenDrawerClose"
          >
            <div v-for="(item, i) in message_list_reverse" :key="i">
              <!-- 判断是不是自己发的 -->
              <div v-if="item.id == uid" style="text-align: right">
                <!-- 判断是否是图片 -->
                <div v-if="item.type == 'img'">
                  <img :src="img_url + item.msg" alt="" style="width: 90px" />:
                  <a-avatar :src="img_url + item.photo" />
                </div>

                <!-- 判断是否是MP3 -->
                <div v-else-if="item.type == 'mp3'">
                  <img :src="img_url + item.photo" />
                </div>

                <!-- 判断是否是msg -->
                <div v-else>
                  {{ item.msg }}:
                  <a-avatar :src="img_url + item.photo" />
                </div>
              </div>

              <!-- 判断是不是自己发的 -->
              <div v-else>
                <!-- 判断是否是图片 -->
                <div v-if="item.type == 'img'">
                  <img :src="img_url + item.msg" alt="" style="width: 90px" />:
                  <a-avatar :src="img_url + item.photo" />
                </div>

                <!-- 判断是否是MP3 -->
                <div v-else-if="item.type == 'mp3'">
                  <img :src="img_url + item.photo" />
                </div>

                <!-- 判断是否是msg -->
                <div v-else>
                  <a-avatar :src="img_url + item.photo" />
                  ：{{ item.msg }}

                </div>
              </div>

              <!-- <div>
                12345
                  <p>{{ item.username }}</p>
                {{item.msg}}
                                <a-avatar :src="img_url+item.img" /> 

                </div> -->

              <!-- <div>
                <p>{{ item.username }}</p>
                <a-avatar :src="img_url+item.img" />
                {{ item.msg }}
              </div> -->
            </div>
            <span v-if="showevaluat && user_id==0">
              请给客服评分：
              <a-rate v-model="evaluate_value" :tooltips="desc" />
              <span class="ant-rate-text">{{ desc[evaluate_value - 1] }}</span>
              <a-button type="primary" @click="addevaluate">
                确定评价
              </a-button>
            </span>
            <div
              :style="{
                position: 'absolute',
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e8e8e8',
                padding: '10px 16px',
                textAlign: 'right',
                left: 0,
                background: '#fff',
                borderRadius: '0 0 4px 4px',
              }"
            >
              <!-- <input type="text" v-model="message" /> -->
              <VueEmoji ref="emoji" @input="onInput" />

              <a-button type="primary" @click="send_msg"> Submit </a-button>

              <!-- 文件上传 -->
              <a-upload
                name="file"
                :multiple="true"
                :action="
                  'http://192.168.1.65:8000/myapp/msgimg/?id=' +
                  user_id +
                  '&uid=' +
                  uid
                "
                :headers="headers"
                @change="handleChange"
                :remove="handleFileRemove"
              >
                <a-button> <a-icon type="upload" /> Click to Upload </a-button>
                <a-avatar
                  :src="img_url + img_name"
                  style="margin-left: 30px"
                  v-show="img_name"
                />
              </a-upload>
            </div>
          </a-drawer>
        </a-drawer>

        <span>
          <!-- <a-form-item label="徽标" v-bind="formlayout">
                



              </a-form-item> -->
          <a-badge count="2" style="margin-left: 60%">
            <img src="static\邮件图标.jpg" style="width: 20px" />
            <a href="#" class="head-example" />
          </a-badge>

          <a-badge :count="num" style="margin-left: 1%" @click="jumpto">
            <img src="static\铃铛.jpg" style="width: 20px" />
            <a href="#" class="head-example" />
          </a-badge>

          <a-badge count="3" style="margin-left: 30px">
            <img src="static\旗帜.jpg" style="width: 20px" />
            <a href="#" class="head-example" />
          </a-badge>

          <a-avatar
            :src="'data:image/' + type + ';base64,' + photo_url"
            style="margin-left: 30px"
          />
          {{ username }}
        </span>
      </a-col>
    </a-row>
  </a-layout-header>
</template>


<script>
import {
  get_user_img,
  getonlineuser,
  send_message,
  delete_msg,
  get_msg,
  send_message_server,
} from "./axios_http/api";
import VueEmoji from "emoji-vue";
export default {
  data() {
    return {
      // 定义一个公共变量接收倒计时
      clock: null,
      // 定义倒计时时间
      final_time: 60*5,
      showevaluat: false,
      evaluate_value: 3,
      desc: ["很差", "差", "一般", "棒", "很棒"],
      people_num: 0,
      myText: "",
      uid: localStorage.getItem("uid"),
      img_url: "http://192.168.1.65:8000/static/upload/",
      img_name: "",
      user_id: null,
      message: "",
      visible: false,
      childrenDrawer: false,
      online_list: [],
      message_list: [],
      num: localStorage.getItem("num"),
      message_num: null,
      // is_pop_up:false,
      collapsed: false,
      username: localStorage.getItem("username"),
      photo_url: "",
      type: "",
      headers: {
        authorization: "authorization-text",
      },
      // 表单样式
      formlayout: {
        // 标签
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        // 文本框
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
      },
    };
  },
  computed: {
    // 将消息列表倒叙
    message_list_reverse() {
      return this.message_list.reverse();
    },
  },
  methods: {
    //倒计时
    countDown() {
      this.clock = window.setInterval(() => {
        console.log(this.final_time)
        this.final_time--;
        if (this.final_time == 0) {
          // 倒计时结束后把评价的状态改成true
          console.log("倒计时结束");
          this.showevaluat = true;
          // 倒计时结束把自己停掉
          clearInterval(this.clock)

        }
      }, 1000);
    },

    // 评价
    addevaluate() {
      var grade = this.evaluate_value * 20;
      console.log("用户评价了：", grade, "分");
    },

    // uid是发送人的id，user_id是接收人的id
    // 获取聊天记录
    g_msg() {
      get_msg({ send_id: this.user_id, receipt_id: this.uid }).then((resp) => {
        console.log(resp);
        this.message_list = resp.data;
      });
    },
    // 绑定输入框内容，用message变量接收
    onInput(event) {
      // 每次失去焦点后重新赋值倒计时5分钟,并且把之前执行的倒计时停止
      clearInterval(this.clock)
      this.final_time = 60*5;
      if (this.user_id == 0) {
        this.countDown();
      }

      //事件。数据包含文本区域的值
      console.log(">>>", event);
      this.message = event.data;
    },
    clearTextarea() {
      this.$refs.emoji.clear();
    },

    // 发送图片
    handleChange(info) {
      if (info.file.status !== "uploading") {
        console.log(">>>", info.file, info.fileList);
        this.img_name = info.file.name;
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
      this.g_msg();
    },
    // 图片删除
    handleFileRemove(file) {
      const name = file.name;
      console.log(name);
      this.img = "";
      delete_msg({ data: { img_name: name } }).then((resp) => {
        console.log(resp);
      });
      // this.axios.delete('http://localhost:8000/myapp/upload/?name=' + name).then((res) => {
      //     console.log(this.img)
      // })
    },

    // // 发送客服消息
    // send_msg_server(){
    //   send_message_server().then((resp) => {
    //     console.log(resp)
    //   })
    // },

    // 发送消息
    send_msg() {
      console.log(this.message, this.user_id);

      send_message({ msg: this.message, id: this.user_id }).then((resp) => {
        console.log(resp);
        this.g_msg();
      });
    },

    // 获取在线人
    get_onlineuser() {
      getonlineuser().then((resp) => {
        console.log(resp);
      });
    },
    showDrawer() {
      getonlineuser().then((resp) => {
        console.log(">>>", resp);
        this.people_num = resp.people_num;
        this.online_list = resp.data;
      });
      this.visible = true;
    },
    onClose() {
      this.visible = false;
    },
    showChildrenDrawer(id) {
      // 再次点开聊天窗时把显示评价客服改为false
      this.showevaluat = false
      // 根据id指定给那个用户发送
      console.log(id);
      this.user_id = id;

      // 发起请求获取聊天记录
      console.log(">>>", this.uid, this.user_id);
      get_msg({ send_id: this.user_id, receipt_id: this.uid }).then((resp) => {
        console.log(resp);
        this.message_list = resp.data;
      });

      this.childrenDrawer = true;
    },
    onChildrenDrawerClose() {
      this.childrenDrawer = false;
    },
    jumpto() {
      this.$router.push("/messageinfo");
    },

    delete_userinfo() {
      localStorage.clear();
      this.$router.push("/login");
    },
  },
  components: {
    VueEmoji,
  },
  created() {
    get_user_img().then((resp) => {
      this.photo_url = resp.img;
      this.type = resp.type;
    });

    // 判断浏览器是否支持websocket
    if ("WebSocket" in window) {
      var _this = this;
      console.log("支持");
      // 生产websocket链接
      var ws = new WebSocket("ws://192.168.1.65:8000/myapp/messagewebsocket/");

      // 发送链接请求
      ws.onopen = function () {
        console.log("JWT " + localStorage.getItem("token"));
        ws.send("JWT " + localStorage.getItem("token"));
      };

      // 发送消息
      ws.onmessage = (evt) => {
        // 将获取信息打印
        // console.log(">>>",typeof(evt.data));

        _this.message_list.push(JSON.parse(evt.data));
        console.log(_this.message_list);
      };
      // 捕获关闭链接
      ws.onclose = function () {
        console.log("链接已经关闭");
      };
    }
  },
};
</script>